package com.cloudcross.ssp.web.operator.main.ad;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Advertiser;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.ILogService;

@Controller("operator.AdvertiserReportController")
@RequestMapping("/operator/main/ad/advertiser")
public class AdvertiserController extends SimpleController {

    @Autowired
    protected IAdvertiserService advertiserService;
    @Autowired
    private ILogService          logService;

    /**
     * @return 返回到广告主管理第一页。
     */
    @RequestMapping
    public String index() {
        return redirect(page("list"));
    }

    @RequestMapping("/list")
    public String list(Model model, @RequestParam HashMap<String, Object> paramMap,
                       @RequestParam(defaultValue = "2") int status, @RequestParam(defaultValue = "1") int page) {

        //按状态搜索用
        if (status != 2) {
            paramMap.put("status", new Integer(status));
        } else {
            paramMap.put("status", null);
        }
        int totalRow = advertiserService.countByParams(paramMap);

        // 查询总行数
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        List<Advertiser> advertiserList = advertiserService.findByParams(paramMap, pager);
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("advertiserList", advertiserList);
        return page("list");
    }

    @RequestMapping("/edit/{id}")
    public String edit(Model model, @PathVariable long id) {
        // 根据id从数据库中查询广告主对象。
        Advertiser advertiser = advertiserService.findById(id);
        model.addAttribute("advertiser", advertiser);
        return page("edit");
    }

    /**
     * @return 创建广告主账号。
     */
    @RequestMapping("/create")
    public String create() {
        return page("create");
    }

    @RequestMapping("/update")
    public String update(Model model, @RequestParam HashMap<String, Object> paramMap, @RequestParam Long advertiserId,
                         @RequestParam(defaultValue = "1") int page) {
        // 查询总行数
        paramMap.put("tableName", "t_advertiser");
        paramMap.put("recordId", advertiserId);
        int totalRow = logService.countByParams(paramMap, "Advertiser");
        Pager pager = new Pager();
        pager.setPage(page);
        pager.setTotalRow(totalRow);
        //向修改记录的页面传logList
        List<Log> logList = logService.findByParams(paramMap, pager, "Advertiser");
        model.addAllAttributes(paramMap);
        model.addAttribute("pager", pager);
        model.addAttribute("logList", logList);
        model.addAttribute("advertiserId", advertiserId);
        return page("update");
    }

    @RequestMapping("/save")
    public String save(Model model, @ModelAttribute("form") Advertiser t) {
        // 校验参数
        //添加用户
        if (t.getId() == null) {
            if (advertiserService.add(t)) {
                Log log = new Log();
                log.setModule("Advertiser");//对应模块
                log.setTableName("t_advertiser");//对应的表名
                //从表中查到新增advertiser的id
                long newId = advertiserService.findByName(t.getName());
                log.setRecordId(newId);//对应广告主id
                log.setActionType("新增");
                log.setAction("新增广告主: " + t.getName());
                //下面这几个字段目前后端数据没有得到。所以仅作测试用！
                log.setActionTime("100");
                log.setAccountId(new Long(1));
                log.setUserIp("122.123.165.11");
                log.setAccountName("内部");
                logService.add(log);
            }
        } else {
            Advertiser formerAdvertiser = advertiserService.findById(t.getId());
            if (advertiserService.edit(t)) {
                String s = t.getName() + "：";
                if (!formerAdvertiser.getName().equals(t.getName())) {
                    s = s.concat("广告主名  " + formerAdvertiser.getName() + " > " + t.getName() + " / ");
                }
                if (!formerAdvertiser.getHomePage().equals(t.getHomePage())) {
                    s = s.concat("网址  " + formerAdvertiser.getHomePage() + " > " + t.getHomePage() + " / ");
                }

                if (!formerAdvertiser.getRegName().equals(t.getRegName())) {
                    s = s.concat("公司名  " + formerAdvertiser.getRegName() + " > " + t.getRegName() + " ");
                }

                if (!formerAdvertiser.getContacts().equals(t.getContacts())) {
                    s = s.concat("联系人  " + formerAdvertiser.getContacts() + " > " + t.getContacts() + " / ");
                }
                if (!formerAdvertiser.getTel().equals(t.getTel())) {
                    s = s.concat("电话  " + formerAdvertiser.getTel() + " > " + t.getTel() + " / ");
                }

                if (!formerAdvertiser.getEmail().equals(t.getEmail())) {
                    s = s.concat("邮箱  " + formerAdvertiser.getEmail() + " > " + t.getEmail() + " / ");
                }

                if (!formerAdvertiser.getMemo().equals(t.getMemo())) {
                    s = s.concat("备注  " + formerAdvertiser.getMemo() + " > " + t.getMemo());
                }
                //如果编辑广告主成功，向log数据库中插入记录
                Log logModify = new Log();
                logModify.setModule("Advertiser");//对应模块
                logModify.setTableName("t_advertiser");//对应的表名
                logModify.setRecordId(t.getId());//对应广告主id
                logModify.setActionType("编辑"); //操作类型
                logModify.setAction(s);//变更详情
                //下面这几个字段目前后端数据没有得到。所以仅作测试用！
                logModify.setActionTime("100");
                logModify.setAccountId(new Long(2));
                logModify.setUserIp("192.168.1.145");
                logModify.setAccountName("内部");
                logService.add(logModify);
            }
        }
        // 跳转到管理页面。
        return redirect(page("list"));
    }

    @RequestMapping("enable")
    public @ResponseBody String enable(Long[] id) {
        if (ArrayUtils.isNotEmpty(id)) {
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < id.length; i++) {
                Advertiser advertiser = advertiserService.findById(new Long(id[i]));
                list.add(advertiser.getName());
            }
            if (advertiserService.updateStatus(LangUtil.array2List(id), Status.enable.value)) {
                for (int i = 0; i < list.size(); i++) {
                    Log log = new Log();
                    log.setModule("Advertiser");//对应模块
                    log.setTableName("t_advertiser");//对应的表名
                    log.setRecordId(id[i]);//对应订单id
                    log.setActionType("启用"); //操作类型
                    log.setAction("启用广告主: " + list.get(i));//变更详情,广告主名称
                    //下面这几个字段目前后端数据没有得到。所以仅作测试用！
                    log.setActionTime("100");
                    log.setAccountId(new Long(3));
                    log.setUserIp("192.168.1.145");
                    log.setAccountName("cloud");
                    logService.add(log);
                }
            }
        }
        return OK;
    }

    @RequestMapping("disable")
    public @ResponseBody String disable(Long[] id) {
        if (ArrayUtils.isNotEmpty(id)) {
            //循环得到订单名称（批量或者单个都可以）___为了插入log记录的时候显示订单名称！_
            List<String> list = new ArrayList<String>();
            for (int i = 0; i < id.length; i++) {
                Advertiser advertiser = advertiserService.findById(new Long(id[i]));
                list.add(advertiser.getName());
            }
            if (advertiserService.updateStatus(LangUtil.array2List(id), Status.disable.value)) {
                //如果禁用订单成功，向log数据库中插入记录！
                for (int i = 0; i < id.length; i++) {
                    Log log = new Log();
                    log.setModule("Advertiser");//对应模块
                    log.setTableName("t_advertiser");//对应的表名
                    log.setRecordId(id[i]);//对应订单id
                    log.setActionType("停用"); //操作类型
                    log.setAction("停用广告主: " + list.get(i));//变更详情,订单名称
                    //下面这几个字段目前后端数据没有得到。所以仅作测试用！
                    log.setActionTime("100");
                    log.setAccountId(new Long(1));
                    log.setUserIp("192.168.1.145");
                    log.setAccountName("cloud");
                    logService.add(log);
                }
            }
        }
        return OK;
    }

    @RequestMapping("delete")
    public @ResponseBody String delete(Long[] id) {
        if (ArrayUtils.isNotEmpty(id)) {
            //循环得到订单名称（批量或者单个都可以）_________为了插入log记录的时候显示订单名称！
            List<String> list = new ArrayList<String>();

            for (int i = 0; i < id.length; i++) {
                Advertiser a = advertiserService.findById(new Long(id[i]));
                list.add(a.getName());
            }

            if (advertiserService.updateStatus(LangUtil.array2List(id), Status.delete.value)) {
                //如果删除订单成功，向log数据库中插入记录！
                for (int i = 0; i < id.length; i++) {
                    Log logDel = new Log();
                    logDel.setModule("Advertiser");//对应模块
                    logDel.setTableName("t_advertiser");//对应的表名
                    logDel.setRecordId(id[i]);//对应广告主id
                    logDel.setActionType("删除"); //操作类型
                    logDel.setAction("删除了广告主:" + list.get(i));//变更详情
                    //下面这几个字段目前后端数据没有得到。所以仅作测试用！
                    logDel.setActionTime("100");
                    logDel.setAccountId(new Long(1));
                    logDel.setUserIp("192.168.1.145");
                    logDel.setAccountName("你好");
                    logService.add(logDel);
                }

            }
        }
        return OK;
    }
}
